package com.markbuikema.juliana32.fragment;

import java.util.List;

import uk.co.senab.actionbarpulltorefresh.library.ActionBarPullToRefresh;
import uk.co.senab.actionbarpulltorefresh.library.Options;
import uk.co.senab.actionbarpulltorefresh.library.PullToRefreshLayout;
import uk.co.senab.actionbarpulltorefresh.library.listeners.OnRefreshListener;
import uk.co.senab.actionbarpulltorefresh.library.viewdelegates.ViewDelegate;
import android.animation.Animator;
import android.animation.Animator.AnimatorListener;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.DecelerateInterpolator;
import android.widget.ImageButton;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.facebook.Session;
import com.markbuikema.juliana32.MainActivity;
import com.markbuikema.juliana32.R;
import com.markbuikema.juliana32.adapter.NieuwsAdapter;
import com.markbuikema.juliana32.asynctask.NieuwsRetriever;
import com.markbuikema.juliana32.model.nieuws.NieuwsItem;
import com.markbuikema.juliana32.model.nieuws.NieuwsItem.OnContentLoadedListener;
import com.markbuikema.juliana32.util.Constants;
import com.markbuikema.juliana32.util.DataManager;
import com.origamilabs.library.views.StaggeredGridView;
import com.origamilabs.library.views.StaggeredGridView.OnScrollDirectionChangeListener;

public class NieuwsFragment extends Fragment {

	private int columnCount;
	private int itemMargin;
	private ActionButtonState state = ActionButtonState.INVISIBLE;

	private TextView emptyState;
	private StaggeredGridView nieuwsList;
	private PullToRefreshLayout ptrLayout;
	private ImageButton actionButton;
	private ProgressBar alternativeLoader;

	private NieuwsAdapter adapter;
	private NieuwsRetriever nieuwsRetriever;

	@Deprecated
	private NieuwsDetail nieuwsDetail;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Resources res = getResources();

		columnCount = res.getInteger(R.integer.column_count);
		itemMargin = res.getDimensionPixelSize(R.dimen.card_margin);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

		View view = inflater.inflate(R.layout.fragment_nieuws, null);

		emptyState = (TextView) view.findViewById(R.id.nieuws_empty_state);
		nieuwsList = (StaggeredGridView) view.findViewById(R.id.nieuws_list);
		ptrLayout = (PullToRefreshLayout) view.findViewById(R.id.nieuws_list_refresher);
		actionButton = (ImageButton) view.findViewById(R.id.action_scroll_up);
		alternativeLoader = (ProgressBar) view.findViewById(R.id.alternative_loader);

		actionButton.setAlpha(0f);
		actionButton.setScaleX(.5f);
		actionButton.setScaleY(.5f);
		actionButton.setVisibility(View.GONE);
		actionButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				nieuwsList.setSelectionToTop();
				setActionButtonVisibile(false);
			}
		});

		nieuwsList.setOnScrollDirectionChangeListener(new OnScrollDirectionChangeListener() {
			@Override
			public void onScrollDirectionChange(boolean scrollingDown) {
				setActionButtonVisibile(!scrollingDown && !nieuwsList.isAtTop());
			}
		});

		adapter = new NieuwsAdapter(getActivity());
		nieuwsList.setAdapter(adapter);

		ActionBarPullToRefresh.from(getActivity()).allChildrenArePullable().listener(new OnRefreshListener() {

			@Override
			public void onRefreshStarted(View view) {
				refresh(true);
			}
		}).useViewDelegate(StaggeredGridView.class, new ViewDelegate() {

			@Override
			public boolean isReadyForPull(View view, float x, float y) {
				if (!(view instanceof StaggeredGridView))
					return false;

				StaggeredGridView sgv = (StaggeredGridView) view;
				boolean atTop = sgv.getChildCount() == 0 || (sgv.getFirstPosition() == 0 && sgv.getChildAt(0).getTop() == itemMargin);
				return atTop;
			}
		}).options(Options.create().noMinimize().headerLayout(R.layout.header).build()).setup(ptrLayout);

		emptyState.setText("");
		if (adapter.getCount() == columnCount) {
			refresh(false);
		}

		return view;
	}

	public void refresh(final boolean usePtrLoader) {
		SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
		boolean facebook = prefs.getBoolean(Constants.KEY_FACEBOOK, true);
		boolean website = prefs.getBoolean(Constants.KEY_WEBSITE, true);

		nieuwsRetriever = new NieuwsRetriever(facebook, website) {

			@Override
			protected void onPreExecute() {
				nieuwsList.animate().translationY(nieuwsList.getHeight()).setDuration(350).setInterpolator(new AccelerateInterpolator()).alpha(0.2f).setListener(new AnimatorListener() {

					@Override
					public void onAnimationStart(Animator animation) {
					}

					@Override
					public void onAnimationRepeat(Animator animation) {
					}

					@Override
					public void onAnimationEnd(Animator animation) {
						adapter.clear();

					}

					@Override
					public void onAnimationCancel(Animator animation) {
					}
				}).start();
				if (usePtrLoader)
					ptrLayout.setRefreshing(true);
				else {
					alternativeLoader.setVisibility(View.VISIBLE);
					emptyState.setVisibility(View.VISIBLE);
					emptyState.setText("Nieuws laden...");
				}

			}

			@Override
			protected void onPostExecute(List<NieuwsItem> result) {
				DataManager.getInstance().setNieuwsItems(result);
				adapter.update();

				// if (itemRequestId != null) {
				//
				// NieuwsItem item =
				// DataManager.getInstance().getNieuwsItemById(itemRequestId);
				// if (item != null)
				// activity.requestNieuwsDetailPage(item, null);
				//
				// itemRequestId = null;
				// }

				if (usePtrLoader)
					ptrLayout.setRefreshComplete();
				else {
					emptyState.setVisibility(View.GONE);
					alternativeLoader.setVisibility(View.GONE);
				}

				nieuwsList.animate().translationY(0).alpha(1f).setDuration(350).setInterpolator(new DecelerateInterpolator()).setListener(null).start();
				boolean empty = adapter.getCount() <= columnCount;
				emptyState.setText(empty ? getResources().getString(R.string.nieuws_empty_state) : "");
				emptyState.setVisibility(empty ? View.VISIBLE : View.GONE);

			}
		};

		nieuwsRetriever.execute();
	}

	public void invalidate() {
		if (adapter != null)
			adapter.notifyDataSetChanged();
	}

	public void search(String s) {
		if (adapter == null)
			return;
		adapter.setSearchword(s);
		if (adapter.getCount() <= columnCount)
			if (ptrLayout.isRefreshing())
				emptyState.setText(R.string.nieuws_empty_state);
			else
				emptyState.setText(R.string.nieuws_loading);
		else
			emptyState.setText("");

	}

	public void clearSearch() {
		if (adapter != null) {
			nieuwsList.animate().translationY(nieuwsList.getHeight()).setDuration(350).setInterpolator(new AccelerateInterpolator()).alpha(0.2f).setListener(new AnimatorListener() {

				@Override
				public void onAnimationStart(Animator animation) {
				}

				@Override
				public void onAnimationRepeat(Animator animation) {
				}

				@Override
				public void onAnimationEnd(Animator animation) {
					adapter.clearSearchword();
					nieuwsList.animate().translationY(0).alpha(1f).setDuration(350).setInterpolator(new DecelerateInterpolator()).setListener(null).start();
				}

				@Override
				public void onAnimationCancel(Animator animation) {
				}
			}).start();
		}
	}

	private void setActionButtonVisibile(boolean visible) {
		if ((state == ActionButtonState.VISIBLE || state == ActionButtonState.ANIM_TO_VISIBLE) && !visible) {
			actionButton.animate().scaleX(.7f).scaleY(.7f).alpha(0f).setDuration(350).setListener(new AnimatorListener() {

				@Override
				public void onAnimationStart(Animator animation) {
				}

				@Override
				public void onAnimationRepeat(Animator animation) {
				}

				@Override
				public void onAnimationEnd(Animator animation) {
					state = ActionButtonState.INVISIBLE;
					actionButton.setVisibility(View.GONE);
				}

				@Override
				public void onAnimationCancel(Animator animation) {
				}
			}).start();
			state = ActionButtonState.ANIM_TO_INVISIBLE;
		} else if ((state == ActionButtonState.INVISIBLE || state == ActionButtonState.ANIM_TO_INVISIBLE) && visible) {
			actionButton.animate().scaleX(1).scaleY(1).alpha(1).setDuration(350).setListener(new AnimatorListener() {

				@Override
				public void onAnimationStart(Animator animation) {
					actionButton.setVisibility(View.VISIBLE);
				}

				@Override
				public void onAnimationRepeat(Animator animation) {
				}

				@Override
				public void onAnimationEnd(Animator animation) {
					state = ActionButtonState.VISIBLE;
				}

				@Override
				public void onAnimationCancel(Animator animation) {
				}
			}).start();
			state = ActionButtonState.ANIM_TO_VISIBLE;
		}
	}

	private enum ActionButtonState {
		VISIBLE,
		INVISIBLE,
		ANIM_TO_VISIBLE,
		ANIM_TO_INVISIBLE
	}

	public void openNieuwsDetail(final NieuwsItem item, final View clickedView) {

		((MainActivity) getActivity()).onNieuwsDetailOpened();

		if (!item.isContentLoaded()) {
			item.startLoading(new OnContentLoadedListener() {

				@Override
				public void onContentLoaded(String content, List<String> photos) {
					openNieuwsDetail(item, clickedView);
				}
			});
			// loader.setVisibility( View.VISIBLE );
			return;
		}
		// loader.setVisibility( View.GONE );

		nieuwsDetail = new NieuwsDetail((MainActivity) this.getActivity(), clickedView, item);

		// Fragment fragment = NieuwsDetailFragment.create(item, view);
		// getFragmentManager().beginTransaction().add(R.id.content_frame,
		// fragment,
		// NieuwsDetailFragment.class.getName()).addToBackStack("NieuwsDetailView").commit();
		nieuwsList.setScrollingEnabled(false);
		nieuwsList.setEnabled(false);
		actionButton.setVisibility(View.GONE);
		nieuwsList.animate().alpha(.1f).setDuration(150).start();

	}

	public boolean isNieuwsDetail() {
		return nieuwsDetail != null;
	}

	public void hideNieuwsDetail() {

		if (nieuwsDetail == null)
			return;

		nieuwsDetail.hide();
		nieuwsDetail = null;

		nieuwsList.setScrollingEnabled(true);
		nieuwsList.setEnabled(true);
		nieuwsList.animate().alpha(1).setDuration(150).start();

		((MainActivity) getActivity()).onNieuwsDetailClosed();

	}

	public String getItemTitle() {
		if (isNieuwsDetail()) {
			return nieuwsDetail.getTitle();
		} else {
			return null;
		}
	}

	public String getItemContent() {
		if (isNieuwsDetail()) {
			return nieuwsDetail.getContent();
		} else {
			return null;
		}
	}

	public void updateFacebookStatus(Session session) {
		if (isNieuwsDetail()) {
			nieuwsDetail.onFacebookSessionChange(session);
		}
	}

}
